//
//  AppDelegate.m
//  Pacific_Computer
//
//  Created by 范琦 on 14-12-17.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "AppDelegate.h"
#import "Infor_Main_ViewController.h"
#import "Forum_Main_ViewController.h"
#import "Product_Main_ViewController.h"
#import "MineViewController.h"
#import "PhotoListViewController.h"
#import "WeiboSDK.h"
#import "NetHandler.h"
#import "UIColor+AddColor.h"


@interface AppDelegate () <WeiboSDKDelegate,UIAlertViewDelegate>

@property (nonatomic,retain) UIView *nigView;
@property (nonatomic,retain) UIImageView *nightImage;
@property (nonatomic,retain) UIActivityIndicatorView *activi;
@property (nonatomic,retain) UIAlertView *alert;

@end

#define KAppKey         @"4266276295"
#define KRedirectURI    @"http://api.weibo.com/oauth2/default.html"

@implementation AppDelegate
- (instancetype)init
{
    self = [super init];
    if (self) {
        
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(receiveNotifica:) name:@"heiyejianglin" object:nil];
        
        NSNotificationCenter *center2 = [NSNotificationCenter defaultCenter];
        [center2 addObserver:self selector:@selector(receiveNotifica2:) name:@"limingjianglin" object:nil];
        
    }
    return self;
}
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}

- (void)receiveNotifica:(NSNotification *)center
{
    
    
    //1.UIView动画
    [UIView animateWithDuration:0.5 animations:^{
        
        self.nightImage.frame = CGRectMake(0, 0, self.window.bounds.size.width, self.window.bounds.size.height);
        self.nigView.hidden = NO;

        
    }];
    
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            self.nightImage.frame = CGRectMake(0, self.window.bounds.size.height, self.window.bounds.size.width, self.window.bounds.size.height);
            self.nigView.hidden = NO;
        
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        UIImage *image = [UIImage imageNamed:@"baitian.jpg"];
        self.nightImage.image = image;
    });
}

- (void)receiveNotifica2:(NSNotification *)center
{
    
    
    //1.UIView动画
    [UIView animateWithDuration:0.5 animations:^{
        
        self.nightImage.frame = CGRectMake(0, 0, self.window.bounds.size.width, self.window.bounds.size.height);
        
        
        
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.nightImage.frame = CGRectMake(0, self.window.bounds.size.height, self.window.bounds.size.width, self.window.bounds.size.height);
        self.nigView.hidden = YES;


        
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            UIImage *image = [UIImage imageNamed:@"wanshang.jpg"];
            self.nightImage.image = image;
   
    });
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:KAppKey];
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [_window release];
    
    Infor_Main_ViewController *infor = [[Infor_Main_ViewController alloc]init];
    infor.title = @"资讯";
    UIImage *imageZixun = [UIImage imageNamed:@"zixun3.png"];
    imageZixun = [imageZixun imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    infor.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"资讯" image:imageZixun tag:1000];
    
    Forum_Main_ViewController *forum = [[Forum_Main_ViewController alloc]init];
    forum.title = @"论坛";
    UIImage *imageForum = [UIImage imageNamed:@"luntan3.png"];
    imageForum = [imageForum imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    forum.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"论坛" image:imageForum tag:2000];
    
    
    Product_Main_ViewController *product = [[Product_Main_ViewController alloc]init];
    product.title = @"找产品";
    UIImage *imageProduct = [UIImage imageNamed:@"sousuo3.png"];
    imageProduct = [imageProduct imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    product.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"找产品" image:imageProduct tag:3000];
    
    MineViewController *mine = [[MineViewController alloc]init];
    mine.title = @"我的";
    UIImage *imageMy = [UIImage imageNamed:@"geren3.png"];
    imageMy = [imageMy imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    mine.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"我的" image:imageMy tag:4000];
    
    PhotoListViewController *photo = [[PhotoListViewController alloc]init];
    photo.title = @"图赏";
    UIImage *imagePhoto = [UIImage imageNamed:@"tupian3.png"];
    imagePhoto = [imagePhoto imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    photo.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"图赏" image:imagePhoto tag:5000];
    
    
    UINavigationController *inforNavi = [[UINavigationController alloc]initWithRootViewController:infor];
    
    UINavigationController *forumNavi = [[UINavigationController alloc]initWithRootViewController:forum];
    
    UINavigationController *productNavi = [[UINavigationController alloc]initWithRootViewController:product];
    
    UINavigationController *photoNavi = [[UINavigationController alloc]initWithRootViewController:photo];
    
    UINavigationController *mineNavi = [[UINavigationController alloc]initWithRootViewController:mine];
    
    
    NSArray *arr = [NSArray arrayWithObjects:inforNavi, forumNavi, productNavi, photoNavi, mineNavi, nil];
    UITabBarController *tabBar = [[UITabBarController alloc]init];
    self.window.rootViewController = tabBar;
    tabBar.viewControllers = arr;
    tabBar.tabBar.tintColor = [UIColor hongse];
    tabBar.tabBar.selectedImageTintColor = [UIColor hongse];
    

    
    self.nigView = [[UIView alloc] initWithFrame:self.window.bounds];
    self.nigView.userInteractionEnabled = NO;
    self.nigView.hidden = YES;
    self.nigView.backgroundColor = [UIColor blackColor];
    self.nigView.alpha = 0.5;
    [self.window addSubview:self.nigView];
    [_nigView release];


//    self.nightImage = [[UIImageView alloc] initWithFrame:CGRectMake(- self.window.bounds.size.width, self.window.bounds.size.height * 36.73 / 100, self.window.bounds.size.width * 46.66 / 100, self.window.bounds.size.height * 26.23 / 100)];
//    UIImage *nigImage = [UIImage imageNamed:@"yueliang1.png"];
//    self.nightImage.image = nigImage;
//    [self.window addSubview:self.nightImage];
//    [_nightImage release];
    
    self.nightImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,self.window.bounds.size.height, self.window.bounds.size.width, self.window.bounds.size.height)];
    UIImage *nigImage = [UIImage imageNamed:@"wanshang.jpg"];
    

    self.nightImage.image = nigImage;
    [self.window addSubview:self.nightImage];
    [_nightImage release];
    

    [NSThread sleepForTimeInterval:1];
    
    
    return YES;
}




- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_nigView release];
    [_nightImage release];
    [_window release];
    [_alert release];
    [super dealloc];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WeiboSDK handleOpenURL:url delegate:self];
    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [WeiboSDK handleOpenURL:url delegate:self];
    
}


//- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
//{
//    [WeiboSDK enableDebugMode:YES];
//    [WeiboSDK registerApp:KAppKey];
//}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        NSString *title = NSLocalizedString(@"发送结果", nil);
        NSString *message = [NSString stringWithFormat:@"%@: %d\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode, NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil),response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];
        WBSendMessageToWeiboResponse* sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse*)response;
        NSString* accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
        if (accessToken)
        {
            self.wbtoken = accessToken;
        }
        NSString* userID = [sendMessageToWeiboResponse.authResponse userID];
        if (userID) {
            self.wbCurrentUserID = userID;
        }
        //[alert show];
        [alert release];
        
        int i = (int)response.statusCode;
        if (i == 0) {
            self.alert = [[UIAlertView alloc] initWithTitle:@"" message:@"分享成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            self.alert.tag = 100;
            [_alert show];
            [_alert release];
            
            [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timeAction:) userInfo:nil repeats:NO];

        }
        
    }

     else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        NSString *title = NSLocalizedString(@"认证结果", nil);
        NSString *message = [NSString stringWithFormat:@"%@: %d\nresponse.userId: %@\nresponse.accessToken: %@\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode,[(WBAuthorizeResponse *)response userID], [(WBAuthorizeResponse *)response accessToken],  NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil), response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];
        self.wbtoken = [response.userInfo objectForKey:@"access_token"];
        //[alert show];
        [alert release];
        

        
        
        
        NSString *token = [response.userInfo objectForKey:@"access_token"];
        NSString *uid = [response.userInfo objectForKey:@"uid"];
        
        NSString *path = [NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?uid=%@&access_token=%@",uid,token];
        
        int i = (int)response.statusCode;
        if (i == 0) {
        UIAlertView *alerter = [[UIAlertView alloc] initWithTitle:@"" message:@"登入成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        alerter.tag = 100;
        [alerter show];
        [alerter release];

        [NetHandler getDataWithUrl:path completion:^(NSData *data) {
            
            NSError *error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:result,@"key", nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"tamenlaile" object:@"香皂" userInfo: dic];

        }];
        }
    }
}

- (void)timeAction:(NSTimer *)time
{
    [self.alert dismissWithClickedButtonIndex:1 animated:YES];
    NSLog(@"fewwwwewfewfwef");
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"value",@"key", nil];
    
    if (alertView.tag == 100) {
        switch (buttonIndex) {
            case 0:
                [[NSNotificationCenter defaultCenter]postNotificationName:@"kuaipao" object:@"香皂" userInfo: dic];
                break;
                
            default:
                break;
        }
    }
}




@end
